#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : GTMS_pytest_auto_api 
@File    : logControl.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/5/20 10:43 
@Describe: 日志记录
"""
import logging
from logging import handlers
import colorlog

from Config.setting import ConfigHandler


class LogHandler(object):
    # 日志级别关系映射
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }
    # 日志记录格式
    log_format = '%(asctime)s - %(name)s:%(filename)s:%(lineno)d - %(levelname)s -> %(message)s'

    def __init__(self, filename, level='info', when='D', backCount=3, fmt=log_format):
        """
        构造函数
        :param filename: 文件名
        :param level: 日志等级
        :param when: 日志备份天数
        :param backCount: 日志备份文件的个数
        :param fmt: 日志记录格式
        """
        self.logger = logging.getLogger(filename)
        # 日志输出颜色配置
        self.log_color_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red'
        }
        # 控制台日志格式配置
        console_log_format = '%(log_color)s[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s'
        formatter = colorlog.ColoredFormatter(console_log_format, log_colors=self.log_color_config)
        # 设置日志文件记录格式
        log_file_format = logging.Formatter(fmt)
        # 设置日志级别
        self.logger.setLevel(self.level_relations.get(level))
        # 控制台输出日志
        console = logging.StreamHandler()
        # 控制台日志格式设置
        console.setFormatter(formatter)
        # 使用TimedRotatingFileHandler实现滚动日志
        log_file = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount, encoding='utf-8')
        # 设置写入文件的日志格式
        log_file.setFormatter(log_file_format)
        # 把对象加到logger里
        self.logger.addHandler(console)
        self.logger.addHandler(log_file)
        self.log_path = ConfigHandler.LOG_PATH


INFO = LogHandler(ConfigHandler.INFO_LOG_PATH, level='info')
ERROR = LogHandler(ConfigHandler.ERROR_LOG_PATH, level='error')
WARNING = LogHandler(ConfigHandler.WARING_LOG_PATH, level='warning')

if __name__ == '__main__':
    WARNING.logger.warning("测试")
